package com.dx.security.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dx.entity.user.Role;
import com.dx.entity.user.User;
import com.dx.security.dto.UserDetailDTO;
import com.dx.security.provider.CustomUserDetailsService;
import com.dx.service.user.RoleService;
import com.dx.service.user.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @author : Yu.Tan
 * @date : 2023/7/22 19:30
 * @desc : this class for xxxxx
 **/
@Service("userDetailsService")
@Slf4j
public class UserDetailsServiceImpl implements CustomUserDetailsService {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Override
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException {
        log.debug("开始登陆验证，用户账号为: {}", phone);
        // 根据用户名账号用户
        User user = userService.getOne(new LambdaQueryWrapper<User>()
                .eq(User::getPhone, phone));
        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException("用户名不存在，登陆失败。");
        }
        UserDetailDTO userDetail=new UserDetailDTO();
        userDetail.setUser(user);
        List<Role> roles=roleService.listRoleByUserId(user.getId());
        userDetail.setRoles(roles);
        return userDetail;
    }

    @Override
    public UserDetails loadUserByUsername(String var1, String var2) throws UsernameNotFoundException {
        log.debug("开始登陆验证，用户账号为: {},{}", var1,var2);
        // 根据用户名账号用户
        User user = userService.getOne(new LambdaQueryWrapper<User>()
                .eq(User::getPhone, var1));
        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException("用户名不存在，登陆失败。");
        }
        UserDetailDTO userDetail=new UserDetailDTO();
        userDetail.setUser(user);
        List<Role> roles=roleService.listRoleByUserId(user.getId());
        userDetail.setRoles(roles);
        return userDetail;
    }
}
